package com.tensquare.article.service;

import com.tensquare.article.dao.ArticleDao;

import com.tensquare.article.pojo.Article;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.concurrent.TimeUnit;


/**
 * & ProjectName：  tensquare-parent
 * & PackageName:   com.tensquare.article.service
 * & Creation_Date： 2020/3/31 01:55
 * & Author：しの
 * ----------------------------------
 * & Description:
 */
@Service
@Transactional
//使用jpa进行增、删、改时，要在service服务类的前面添加@Transactional注解
public class ArticleService {
    @Autowired
    //此处注入的redis不需要在yml文件中配置
    private RedisTemplate redisTemplate;
    @Autowired
    private ArticleDao articleDao;

    //1 文章审核
    public void examine(String articleId) {
        articleDao.examine(articleId);
    }

    //2 文章点赞
    public void thumbup(String articleId) {
        articleDao.thumbup(articleId);
    }

    //3 根据id查询
    public Article findById(String articleId) {
        //1 从redis中得到文章
        Article article = (Article) redisTemplate.opsForValue().get("article_" + articleId);
        //2 判断是否存在
        if (article == null) {
            article = articleDao.findById(articleId).get();
            //放入到缓存中
            //redisTemplate.opsForValue().set("article_" + articleId, article);
            //缓存过期时间处理(比如：下面设置的缓存就是10秒后过期)
             redisTemplate.opsForValue().set("article_"+articleId,article,10, TimeUnit.SECONDS);
        }
        return article;
    }
    public void update(Article article) {
        //清空缓存
        redisTemplate.delete("article_"+article.getId());
        articleDao.save(article);
    }

    public void delete(String id) {
        //清空缓存
        redisTemplate.delete("article_"+id);
        articleDao.deleteById(id);
    }
}
